const utils = require('my-utils')
const db = uniCloud.database()
module.exports = {
	_before: async function() { // 通用预处理器
		this.userInfo = await utils.getUserInfo(this)
		if (!this.userInfo.uid) throw this.userInfo
	},
	async createOrder(data) {
		let newData = {
			...data,
			user_id: this.userInfo.uid,
			order_id: getOrderId(),
			createTime: Date.now(),
			done: false,
		}
		await db.collection('my-mall-order').add(newData)
		return newData.order_id
	},
	async getList() {

		return await db.collection('my-mall-order').where({
			user_id: this.userInfo.uid,
		}).orderBy('createTime', 'desc').get()
	},
	// 管理员获取所有订单
	async getAllList() {
		if (!this.userInfo.role.includes('manage')) {
			return {
				msg: '没有权限',
				code: -1
			}
		}
		return await db.collection('my-mall-order').orderBy('createTime', 'desc').get()
	},
	// 管理员修改订单状态
	async updateDone(id) {
		if (!this.userInfo.role.includes('manage')) {
			return {
				msg: '没有权限',
				code: -1
			}
		}
		return await db.collection('my-mall-order').doc(id).update({
			done: true
		})
	}
}
// 生成订单号
function getOrderId() {
	return Date.now() + '_' + String(Math.random()).substring(3, 9)
}